package dk.ahp.getmeoff;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;

public class MainActivity extends AbstractActivity implements OnClickListener, OnItemClickListener, OnItemLongClickListener {
	private static final String TAG = MainActivity.class.getSimpleName();
	private Button addDestButton;
	private ListView destListView;
	private Map<Integer, String> listPosDestMap = null;
	private TextView statusTV;
	private StatusReceiver statusReceiver = null;
	private IntentFilter statusFilter = null; 
	
    @SuppressLint("UseSparseArrays")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        statusReceiver = new StatusReceiver();
        
        statusTV = (TextView) findViewById(R.id.debugTextView);
        
        addDestButton = (Button) findViewById(R.id.AddDestButton);
        addDestButton.setOnClickListener(this);

        destListView = (ListView) findViewById(R.id.destListView);
        destListView.setOnItemClickListener(this);
        destListView.setOnItemLongClickListener(this);
        
    	// Check if gps is enabled.
    	LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    		dialog.setTitle(getResources().getString(R.string.no_gps));
    		dialog.setMessage(getResources().getString(R.string.go_to_settings));
    		dialog.setPositiveButton(getResources().getString(R.string.yes), new AlertDialog.OnClickListener() {
    			public void onClick(DialogInterface arg0, int arg1) {
    	    		Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    	    		startActivity(settingsIntent);
    			}
    		});
    		dialog.setNegativeButton(getResources().getString(R.string.no), null);
    		AlertDialog dlg = dialog.create();
    		dlg.show(); 
    	}

    	statusTV.setText("Ingen alarm aktiveret");
    	statusFilter = new IntentFilter("dk.ahp.getmeoff.STATUS");
        Log.d(TAG, "onCreate done");
    }
    
    @Override
	public void onResume() {
    	super.onResume();
    	Log.d(TAG, "onResume");
    	
        updateDestListView();

        updateStatus();
        
        View lay = (View) findViewById(R.id.mainRelativeLayout); 
        setBackground(lay);

        registerReceiver(statusReceiver, statusFilter);
    }

	private void updateDestListView() {
		DestinationLogic destLogic = GetMeOffApplication.getMeOffApplication.destinationLogic;
        ArrayList<String> destinations = new ArrayList<String>();
        listPosDestMap = new HashMap<Integer, String>();
        int j=0;
        for(String destName : destLogic.getDestinationNames()) {
        	destinations.add(destName);
        	listPosDestMap.put(j++, destName);
        }
        destListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, destinations));
	}

	private void updateStatus() {
		if (GetMeOffApplication.getMeOffApplication.distanceToDest > 0 && 
        		null != GetMeOffApplication.getMeOffApplication.activeDestination) {
        	String statusText = "Aktiv destination: " +  GetMeOffApplication.getMeOffApplication.activeDestination.getName() + "\n";
        	statusText += "Afstand til bestemmelsessted er " + GetMeOffApplication.getMeOffApplication.distanceToDest + "meter";
        	
        	statusTV.setText(statusText);
        }
	}
    
    @Override
	public void onPause() {
    	super.onPause();
    	unregisterReceiver(statusReceiver);
    }
    
    
	@Override
	public void onClick(View v) {
		if (v == addDestButton) {
			//vis add dest activity
			Log.d(TAG, "onClick starts AddDistActivity");
			startActivity(new Intent(this, AddDestActivity.class));
		} 
		Log.e(TAG, "onClick NOT handeled.");
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		Log.d(TAG, "onItemClick");
		if (listPosDestMap.containsKey(position)) {
			Intent i = new Intent(this, AddDestActivity.class);
			i.putExtra("name", listPosDestMap.get(position));
			startActivity(i);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		Log.d(TAG, "onItemLongClick");
		if (listPosDestMap.containsKey(position)) {
			final int positionToDelete = position;
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
//    		dialog.setTitle(getResources().getString(R.string.delete_destination));
    		dialog.setMessage(getResources().getString(R.string.delete_destination));
    		dialog.setPositiveButton(getResources().getString(R.string.yes), new AlertDialog.OnClickListener() {
    			public void onClick(DialogInterface arg0, int arg1) {
    				//	delete from db.
    	    		GetMeOffApplication.getMeOffApplication.destinationLogic.Delete(listPosDestMap.get(positionToDelete));
    				updateDestListView();
    			}
    		});
    		dialog.setNegativeButton(getResources().getString(R.string.no), null);
    		AlertDialog dlg = dialog.create();
    		dlg.show(); 
		}
		return true;
	}

	/**
	 * BroadcastReceiver, receives status on active destination and updates debugTV. 
	 */
	class StatusReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			updateStatus();
		}
	}
	
}
